<template>
  <view :style="colorStyle">
    <!-- <nodata :value="'car'" /> -->

    <view class="infobox2 flex aitems between">
      <view class="left flex aitems">
        <view class="block1" @click.stop="checkAllChange">
          <radio
            :checked="checkAll"
            color="var(--view-theme)"
            style="transform: scale(0.9)"
          />
        </view>
        <view class="block2 c1F1F1F f32 fontWeight"> 全选 </view>
      </view>
      <view class="right c1F1F1F f28" @click="edit">
        {{ operation ? "完成" : "编辑" }}
      </view>
    </view>

    <view class="" style="height: 100rpx"> </view>

    <view class="infobox3" v-for="(item, index, key) in list" :key="key">
      <view class="block1 flex aitems">
        <view class="info1" @click.stop="checkSellerChange(index)">
          <radio
            :checked="item.check"
            color="var(--view-theme)"
            style="transform: scale(0.9)"
          />
        </view>
        <view
          class="info2 flex aitems"
          @click.stop="gourl(`/pages/seller/info?id=${item.sellerId}`)"
        >
          <image class="tip1" :src="item.sellerLogo" mode=""></image>
          <view class="tip2 c1F1F1F f32 fontWeight">
            {{ item.sellerName }}
          </view>
          <image class="tip3" src="@/static/img15.png" mode=""></image>
        </view>
      </view>
      <view class="block2">
        <view
          class="list flex aitems"
          v-for="(items, indexs, keys) in item.shopCartItems"
          :key="keys"
        >
          <view class="left" @click.stop="checkGoodsChange(index, indexs)">
            <radio
              :checked="items.check"
              color="var(--view-theme)"
              style="transform: scale(0.9)"
            />
          </view>
          <view class="right flex aitems">
            <image
              :src="items.goodsImg"
              class="goodsimg"
              mode="aspectFill"
              @click.stop="gourl(`/pages/goods/detail?id=${items.goodsId}`)"
            ></image>
            <view class="info1 flex between column">
              <view class="tipbox1 ellipsis1 c1F1F1F f28">
                {{ items.goodsName }}
              </view>
              <view class="tipbox1 ellipsis1 c858585 f22">
                {{
                  items.goodsSpec
                    .replace(/{/g, "")
                    .replace(/}/, "")
                    .replace(/"/g, "")
                }}
              </view>
              <view class="tipbox2 flex aitems between">
                <view class="price flex aitems cF65B49 fontWeight">
                  <view class="tip1 f24"> ￥ </view>
                  <view class="tip2 f36">
                    {{ Number(items.goodsPrice).toFixed(2) }}
                  </view>
                </view>
                <view class="step flex aitems" v-if="!operation">
                  <view
                    class="jian flex aitems jcenter"
                    @click.stop="handleJian(index, indexs)"
                  >
                    <image src="@/static/img59.png" mode=""></image>
                  </view>

                  <input
                    class="c1F1F1F f22"
                    type="number"
                    maxlength="5"
                    v-model="items.goodsNum"
                    @blur="goodsnumBlur($event, index, indexs)"
                  />
                  <view
                    class="jia flex aitems jcenter"
                    @click.stop="handleJia(index, indexs)"
                  >
                    <image src="@/static/img58.png" mode=""></image>
                  </view>
                </view>
                <image
                  v-if="operation"
                  @click.stop="delGoods(index, indexs)"
                  src="@/static/img60.png"
                  class="del"
                  mode=""
                ></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <nodata :value="'car'" v-if="list.length == 0" />

    <view class="" style="height: 300rpx"> </view>

    <view class="infobox1 flex between">
      <view class="left"> </view>
      <view class="right flex aitems">
        <view class="block1">
          <view class="info1 flex aitems fontWeight">
            <view class="tip1 c1F1F1F f24"> 合计： </view>
            <view class="tip2 cF65B49 f36">
              ￥{{ Number(totalprice).toFixed(2) }}
            </view>
          </view>
          <view class="info2 c858585 f22"> 共{{ totalNum }}件 </view>
        </view>
        <view class="block2 cfff f32" @click="save">
          {{ operation ? "删除" : "去结算" }}
        </view>
      </view>
    </view>

    <custom-tab-bar :path="'/pages/car/car'" :list="[]"></custom-tab-bar>
  </view>
</template>

<script>
import colors from "@/mixins/color";
import customTabBar from "@/components/CustomTabBar";
import {
  getToken,
  setStorage,
  getStorage,
  removeStorage,
  getGloBalData,
} from "@/utils/storage.js";
import {
  adornInfo,
  cartRemove,
  cartList,
  cartUpdate,
  orderConfirm,
  updateParent,
} from "@/servers/servers.js";
import { HTTP_STATUS } from "@/servers/config.js";
import { loading, showModal, msg, go } from "../../utils/wxAPI";
import { handleLoopCallBack } from "@/utils/util";
import { getEnv } from "../../utils/env";
export default {
  mixins: [colors],
  components: {
    customTabBar,
  },
  data() {
    return {
      checkboxValue1: [],
      checkAll: false,

      list: [],
      operation: false,
      totalprice: "0.00",

      totalNum: 0,
      options: {},
    };
  },
  async onLoad(options) {
    this.options = options;
    uni.hideTabBar();
    if (getToken()) {
      this.cartList();
      if (this.options.uid) {
        updateParent({
          id: this.options.uid,
        });
      }
    } else {
      handleLoopCallBack(async () => {
        this.cartList();
        if (this.options.uid) {
          updateParent({
            id: this.options.uid,
          });
        }
      });
      // #ifdef H5
      if (getEnv() == "H5") {
        uni.reLaunch({
          url: "/pages/login/login",
        });
      }
      // #endif
    }
  },
  onShow() {
    if (getToken()) {
      if (getStorage("carRef")) {
        removeStorage("carRef");
        this.totalprice = "0.00";
        this.checkAll = false;
        this.operation = false;
        this.cartList();
        if (this.options.uid) {
          updateParent({
            id: this.options.uid,
          });
        }
      }
    }
  },
  methods: {
    edit() {
      this.operation = !this.operation;
    },
    async cartList() {
      loading();
      let { data } = await cartList();
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        let list = data.data;
        let list2 = [];
        list.map((item) => {
          list2.push(item);
          item.check = false;
          let goods = [];
          item.shopCartItems.map((items) => {
            items.check = false;
            if (items.goodsStatus == 1) {
              goods.push(items);
              list2.shopCartItems = goods;
            }
          });
        });
        this.list = list;
        console.log(list);
      }
      uni.hideLoading();
      uni.stopPullDownRefresh();
    },
    async handleJian(index, indexs) {
      if (this.list[index].shopCartItems[indexs].goodsNum == 1) {
        return msg("至少1个库存");
      }
      loading();
      let { data } = await cartUpdate({
        id: this.list[index].shopCartItems[indexs].id,
        goodsNumber: this.list[index].shopCartItems[indexs].goodsNum - 1,
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        this.list[index].shopCartItems[indexs].goodsNum =
          this.list[index].shopCartItems[indexs].goodsNum - 1;
        this.orderconfirm();
      }
    },
    async handleJia(index, indexs) {
      loading();
      let { data } = await cartUpdate({
        id: this.list[index].shopCartItems[indexs].id,
        goodsNumber: this.list[index].shopCartItems[indexs].goodsNum + 1,
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        this.list[index].shopCartItems[indexs].goodsNum =
          this.list[index].shopCartItems[indexs].goodsNum + 1;
        this.orderconfirm();
      }
    },

    async goodsnumBlur(e, index, indexs) {
      let num = Number(e.detail.value);
      if (num <= 0) {
        return msg("库存不能为0");
      }
      loading();
      let { data } = await cartUpdate({
        id: this.list[index].shopCartItems[indexs].id,
        goodsNumber: Number(e.detail.value),
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        this.list[index].shopCartItems[indexs].goodsNum = num;
        this.orderconfirm();
      }
    },

    async orderconfirm() {
      let cartIds = [];
      let totalNum = 0;
      this.list.map((item) => {
        item.shopCartItems.map((items) => {
          if (items.check) {
            cartIds.push(items.id);
            totalNum += Number(items.goodsNum);
          }
        });
      });
      this.totalNum = totalNum;
      if (cartIds.length == 0) {
        this.totalprice = "0.00";
        this.totalNum = 0;
        uni.hideLoading();
        return false;
      }
      if (cartIds.length !== 0) {
        loading();
        let { data } = await orderConfirm({
          addrId: 0,
          cartIds: cartIds,
          couponId: 0,
          deductIntegral: 0,
          deductMoney: 0,
          logisticsType: "2",
          orderItem: {},
          orderShopList: [],
        });
        if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
          this.totalprice = data.data.orderPriceTotal;
        } else {
          this.cartList();
        }
        setTimeout(() => {
          uni.hideLoading();
        }, 1000);
      }
    },

    async delGoods(index, indexs) {
      showModal({
        t2: "是否将选中的商品删除？",
      })
        .then(async () => {
          loading();
          let { data } = await cartRemove({
            ids: this.list[index].shopCartItems[indexs].id,
          });
          if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
            msg(data.msg);
            this.operation = false;
            this.cartList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    async save() {
      let ids = [];
      let checkGoodsList = [];
      this.list.map((item) => {
        item.shopCartItems.map((items) => {
          if (items.check) {
            ids.push(items.id);
            checkGoodsList.push(item);
          }
        });
      });
      if (ids.length == 0) {
        return msg("请选择一款商品");
      }
      if (this.operation) {
        showModal({
          t2: "是否将选中的商品删除？",
        }).then(async () => {
          loading();
          let { data } = await cartRemove({
            ids: ids.join(","),
          });
          if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
            msg(data.msg);
            this.cartList();
          }
        });
      } else {
        // #ifdef MP-WEIXIN
        if (!getGloBalData("is_authorization")) {
          return go(`/pages/reg/reg`);
        }
        // #endif
        // #ifdef H5
        if (getEnv() == "WX_PUBLIC") {
          if (!getStorage("is_authorization")) {
            return go(`/pages/reg/reg`);
          }
        }
        // #endif
        go("/pages/goods/confirm?ids=" + ids.join(","));
      }
    },

    checkAllChange() {
      this.checkAll = !this.checkAll;
      if (this.checkAll) {
        this.list.map((item) => {
          item.check = true;
          item.shopCartItems.map((items) => {
            items.check = true;
          });
        });
      } else {
        this.list.map((item) => {
          item.check = false;
          item.shopCartItems.map((items) => {
            items.check = false;
          });
        });
      }
      this.orderconfirm();
    },

    checkSellerChange(index) {
      this.list[index].check = !this.list[index].check;
      if (this.list[index].check) {
        this.list[index].shopCartItems.map((item) => {
          item.check = true;
        });
      } else {
        this.list[index].shopCartItems.map((item) => {
          item.check = false;
        });
      }

      let checkAll = true;
      this.list.map((item) => {
        if (!item.check) {
          checkAll = false;
        }
      });
      if (checkAll) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }

      this.orderconfirm();
    },

    checkGoodsChange(index, indexs) {
      this.list[index].shopCartItems[indexs].check =
        !this.list[index].shopCartItems[indexs].check;
      let sellerCheck = true;
      this.list[index].shopCartItems.map((item) => {
        if (!item.check) {
          sellerCheck = false;
        }
      });
      if (sellerCheck) {
        this.list[index].check = true;
      } else {
        this.list[index].check = false;
      }

      let checkAll = true;
      this.list.map((item) => {
        if (!item.check) {
          checkAll = false;
        }
      });
      if (checkAll) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }

      this.orderconfirm();
    },

    gourl(url) {
      go(url);
    },
  },
  onPullDownRefresh() {
    this.cartList();
  },
  onShareAppMessage: function (e) {
    return {
      title: "购物车",
      path: `/pages/car/car?uid=${getGloBalData("userinfo").id}`,
    };
  },
};
</script>
<style>
/* #ifdef MP-WEIXIN */
page {
  background: #f5f5f5;
}

/* #endif */
</style>
<style lang="scss" scoped>
page {
  background: #f5f5f5;
}

.infobox1 {
  position: fixed;
  /* #ifdef H5 */
  bottom: calc(100rpx + env(safe-area-inset-bottom));
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  /* #endif */
  background: #fff;
  width: 100%;
  padding: 8rpx 0;
  /* #ifdef MP-WEIXIN */
  bottom: calc(100rpx);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  /* #endif */
  z-index: 99;

  .right {
    .block1 {
      .info1 {
        .tip1 {
        }

        .tip2 {
        }
      }

      .info2 {
        text-align: right;
      }
    }

    .block2 {
      margin-left: 20rpx;
      margin-right: 30rpx;
      background: var(--view-theme);
      padding: 20rpx 54rpx;
      border-radius: 63rpx;
    }
  }
}

.infobox2 {
  position: fixed;
  top: 0;
  width: calc(100% - 60rpx);
  padding: 30rpx;
  background: #fff;
  z-index: 99;

  .left {
    .block1 {
    }

    .block2 {
      margin-left: 20rpx;
    }
  }

  .right {
  }
}

.infobox3 {
  margin: 30rpx 30rpx 0;
  background: #fff;
  border-radius: 28rpx;
  padding: 36rpx 24rpx 1rpx;

  .block1 {
    margin: 0 0 36rpx 0;

    .info1 {
    }

    .info2 {
      margin-left: 24rpx;

      .tip1 {
        width: 40rpx;
        height: 40rpx;
      }

      .tip2 {
        margin: 0 12rpx 0 8rpx;
      }

      .tip3 {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .block2 {
    .list {
      margin: 0 0 43rpx 0;

      .left {
      }

      .right {
        margin-left: 24rpx;
        width: calc(100% - 24rpx - 50rpx);

        .goodsimg {
          width: 180rpx;
          height: 180rpx;
          border-radius: 28rpx;
        }

        .info1 {
          width: calc(100% - 180rpx - 20rpx);
          margin-left: 20rpx;
          height: 180rpx;

          .tipbox1 {
          }

          .tipbox2 {
            .price {
              .tip1 {
                position: relative;
                top: 2rpx;
              }

              .tip2 {
              }
            }

            .step {
              .jian {
                width: 40rpx;
                height: 40rpx;
                border-radius: 6rpx;
                border: 1px solid #858585;

                image {
                  width: 17rpx;
                  height: 2rpx;
                }
              }

              input {
                width: 60rpx;
                text-align: center;
              }

              .jia {
                width: 40rpx;
                height: 40rpx;
                border-radius: 6rpx;
                background: var(--view-theme);

                image {
                  width: 17rpx;
                  height: 17rpx;
                }
              }
            }

            .del {
              width: 32rpx;
              height: 32rpx;
            }
          }
        }
      }
    }
  }
}
</style>
